package me.leiusual.sharing.util.extension

import android.text.Spanned
import androidx.core.text.HtmlCompat
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken
import me.leiusual.sharing.util.tool.HtmlTagHandler

/**
 * Create by leiusual on 2018/7/25
 */

fun String?.toImplicitRealName(): String? {
  return if (this != null && length > 1) replaceRange(0, 1, "*") else this
}

fun String?.toImplicitMobile(): String? {
  return if (this != null && length == 11) replaceRange(3, 7, "****") else this
}

fun String?.toImplicitIdCard(): String? {
  return if (this != null && length > 8) replaceRange(4, length - 4, "********") else this
}

fun String.matchesMobile(): Boolean {
  return try {
    this.matches(Regex("""^(13[0-9]|14[57]|15[0-3,5-9]|1[6-9][0-9])[0-9]{8}${'$'}|^6\d{7}${'$'}"""))
  } catch (e: Throwable) {
    e.printStackTrace()
    false
  }
}

fun String.matchesPassword(): Boolean {
  return try {
    this.matches(Regex("""^.*\d+.*${'$'}"""))
        && this.matches(Regex("""^.*[A-Z]+.*${'$'}"""))
        && this.matches(Regex("""^.*[a-z]+.*${'$'}"""))
  } catch (e: Throwable) {
    e.printStackTrace()
    false
  }
}

/**
 * Json字符串转对象
 */
inline fun <reified T> String?.toAny(): T? {
  return try {
    gson.fromJson(this, object : TypeToken<T>() {}.type)
  } catch (e: JsonSyntaxException) {
    e.printStackTrace()
    null
  }
}

/**
 * html to Spanned
 */
fun String.toSpanned(): Spanned {
  val flags = HtmlCompat.FROM_HTML_MODE_COMPACT
  return HtmlCompat.fromHtml(this, flags, null, HtmlTagHandler())
}